<?php
/**博士通-短信验证第三方拓展库
 * User: 明哲
 * Date: 2016/4/14
 * Time: 16:37
 */

class MsgVerify_Lite{

    //短信平台uid
    protected $msg_uid;
    //短信平台密码
    protected $msg_pwd;
    //短信平台绑定ip地址
    protected $msg_ip;
    //短信平台绑定端口号
    protected $msg_port;
    //短信平台绑定长号
    protected $msg_srcphone;
    //短信平台验证码更新频率 单位：秒（s）
    protected $msg_refresh_second;
    //短信平台信息设置
    protected $msg_tpl;

    //初始化配置
    function __construct($msgConfig){
        $this->msg_tpl = $msgConfig['msg_tpl'];
        $this->msg_uid = $msgConfig['msg_uid'];
        $this->msg_pwd = $msgConfig['msg_pwd'];
        $this->msg_ip = $msgConfig['msg_ip'];
        $this->msg_port = $msgConfig['msg_port'];
        $this->msg_srcphone = $msgConfig['msg_srcphone'];
        $this->msg_refresh_second = $msgConfig['msg_refresh_second'];
    }

    /**发送短信
     * @param $mobile_number 发送短信号码
     * @param $msg 信息
     * @return string
     */
    public function send($mobile_number) {
        //生成短信验证码
        $msg_code = $this->generateRand();
        //拼凑短信模板
        $msg_tpl = $this->msg_tpl.$msg_code;
        //短信模板转义
        $encoded_msg=urlencode("$msg_tpl");
        //短信平台请求地址拼凑
        $url="http://$this->msg_ip:$this->msg_port/cmppweb/sendsms?uid=$this->msg_uid&msg=$encoded_msg&srcphone=$this->msg_srcphone&mobile=$mobile_number&pwd=$this->msg_pwd";
        //提交参数拼凑
        $post_data = array(
            'uid' => $this->msg_uid,
            'msg' => $encoded_msg,
            'srcphone' => $this->msg_srcphone,
            'mobile' => $mobile_number,
            'pwd' => $this->msg_pwd
        );
        //curl发送请求
        $curl = new PhalApi_CUrl(2);
        $rs = $curl->post($url, $post_data);
        if($rs==0){
            return $rs;
        }else{
            throw new PhalApi_Exception_InternalServerError('短信平台出现问题',1);
        }
    }

    /**生成手机短信验证码
     * @return int
     */
    public function generateRand() {
        session_start();
        //设置当前时间
        $currentTime = intval(time());

        if(isset($_SESSION['msg']['start_time'])){
            if(($currentTime - $_SESSION['msg']['start_time']) >= intval($this->msg_refresh_second)){
                //设置六位随机数
                $v_code = mt_rand(111111, 999999);
                $_SESSION['msg']['start_time'] = $currentTime;
                $_SESSION['msg']['v_code'] = $v_code;
            }else{
                $v_code = $_SESSION['msg']['v_code'];
            }
        }else{
            //设置六位随机数
            $v_code = mt_rand(111111, 999999);
            $_SESSION['msg']['start_time'] = $currentTime;
            $_SESSION['msg']['v_code'] = $v_code;
        }
        var_dump($v_code);
        return $v_code;
    }

    public function verify($v_code){
        if($v_code == $_SESSION['msg']['v_code'] ){
            return true;
        }else{
            return false;
        }
    }
}